import type {AxiosResponse} from 'axios';
import axios, {InternalAxiosRequestConfig} from 'axios';
import {ApiResult} from "@/request/types/base";
import {showToast} from "vant";

const net = axios.create({
    baseURL: import.meta.env.VITE_API_URL as string
});

// 添加请求拦截器
net.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        return config
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 添加响应拦截器
net.interceptors.response.use((result: AxiosResponse<ApiResult<unknown> | any>) => {
    let res = result.data;

    //在请求头配置了该参数就需要返回原始响应数据
    if(result.config.headers.needOriginData){
        return res
    }

    if (res.code === 0) {
        return res.data
    } else {
        console.log("接口返回错误",res)
        if (res.code == 403) {
            showToast("登录失效")
            // router.push('/login')
        } else {
            showToast(res.msg)
            throw "net stop!"
        }
    }
},(e)=>{
    console.log("请求失败",e)
});


export { net };
